//
//  CallViewController.m
//  AlinkDemo
//
//  Created by Vincent on 2017/10/28.
//  Copyright © 2017年 aliyun. All rights reserved.
//

#import "CallViewController.h"
#import "AppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>
@interface CallViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *videoView;
@property (weak, nonatomic) IBOutlet UIButton *hangupButton;
@property (weak, nonatomic) IBOutlet UIButton *captureButton;
@property (weak, nonatomic) IBOutlet UIButton *audioButton;
@property (weak, nonatomic) IBOutlet UIButton *speakButton;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIView *callView;
@property (weak, nonatomic) IBOutlet UIView *loadingView;
@property (weak, nonatomic) IBOutlet UIImageView *loadingImageView;

//电话进来
@property (weak, nonatomic) IBOutlet UIView *callCommingView;
@property (weak, nonatomic) IBOutlet UIButton *doorCallBeforeHangupButton;
@property (weak, nonatomic) IBOutlet UIButton *videoChatButton;
@property (weak, nonatomic) IBOutlet UIButton *audioChatButton;
//已接通
@property (weak, nonatomic) IBOutlet UIView *callingView;
@property (weak, nonatomic) IBOutlet UIButton *doorCallHangupButton;
@property (weak, nonatomic) IBOutlet UIButton *doorCallAudioButton;
@property (weak, nonatomic) NSTimer *timer;
@property (weak, nonatomic) NSTimer *callTimer;

@property (nonatomic,copy) NSString *sid;
@property (nonatomic,assign) NSInteger seconds;
@property (nonatomic,assign) NSInteger callSeconds;
@property (nonatomic,assign) BOOL canOperate;

@property (nonatomic,strong) NSDateFormatter *dateFormatter;
@property(nonatomic,assign) SystemSoundID soundID;//播放文件标识

- (IBAction)hangupAction:(id)sender;
- (IBAction)captureAction:(id)sender;
- (IBAction)audioSwitchAction:(id)sender;
@end

@implementation CallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.nameLabel.text = self.title;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isPlaying = YES;
    self.dateFormatter = [[NSDateFormatter alloc] init];
    UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc]
                                             initWithTarget:self
                                             action:@selector(myspeakButtonPressed:)];
    gesture.minimumPressDuration = 0;
    [self.speakButton addGestureRecognizer:gesture];
    self.speakButton.layer.cornerRadius=5;
    
    //旋转图片动画
    [self rotateImageView];
    
    NSArray *deviceList = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceList"];
    if (deviceList) {
        
        for (NSDictionary *device in deviceList) {
            
            if ([self.bid isEqualToString:device[@"bid"]]) {
                NSString *nick = device[@"nick"];
                self.nameLabel.text =nick?nick:device[@"name"];
                break;
                
            }
        }
    }


    if (self.isDoolCall) {
        [self.loadingView setHidden:YES];

        SystemSoundID theID= 0;

        //获取要播放音效的URL
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"call" withExtension:@"caf"];

        //将音效的URL桥接为CFURLRef类型的URL
        CFURLRef urlRef = (__bridge CFURLRef)(url);

        //根据音效urlRef生成对应的SystemSoundID(传soundID的地址，生成之后会根据地址找到它并给它赋值)
        AudioServicesCreateSystemSoundID(urlRef, &theID);
        self.soundID = theID;

        //播放音效
        AudioServicesPlaySystemSound(theID);

        self.timeLabel.text =@"有人按门铃";
        [self.callView setHidden:YES];
        [self.callingView setHidden:YES];
        [self.callCommingView setHidden:NO];
//        self.sid = [YKBusinessFramework equesOpenCall:self.bid showView:self.videoView enableVideo:NO];
    }else{
        [self performSelectorOnMainThread:@selector(startCallCount) withObject:nil waitUntilDone:YES];
        [self.callView setHidden:NO];
        [self.callingView setHidden:YES];
        [self.callCommingView setHidden:YES];
        self.sid = [YKBusinessFramework equesOpenCall:self.bid showView:self.videoView enableVideo:YES];
    }
    
    [self initButton:self.hangupButton];
    [self initButton:self.captureButton];
    [self initButton:self.audioButton];
    [self initButton:self.doorCallBeforeHangupButton];
    [self initButton:self.videoChatButton];
    [self initButton:self.audioChatButton];
    [self initButton:self.doorCallHangupButton];
    [self initButton:self.doorCallAudioButton];

       //注册挂断电话通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeCallNotification) name:@"fireCall" object:nil];
    
}

- (void)closeCallNotification{

    [self hangupAction:nil];
}

- (void)rotateImageView {
    // 一秒钟旋转几圈
    CGFloat circleByOneSecond = 2.5f;
    
    // 执行动画
    [UIView animateWithDuration:1.f / circleByOneSecond
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         self.loadingImageView.transform = CGAffineTransformRotate(self.loadingImageView.transform, M_PI_2);
                     }
                     completion:^(BOOL finished){
                         [self rotateImageView];
                     }];
}

-(void)initButton:(UIButton*)btn{
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使图片和文字水平居中显示
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0.0 ,-btn.imageView.frame.size.width, -btn.imageView.frame.size.height,0.0)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
    [btn setImageEdgeInsets:UIEdgeInsetsMake(-btn.imageView.frame.size.height, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//图片距离右边框距离减少图片的宽度，其它不边
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isPlaying = YES;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageResult:) name:equesOnMessageResultNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVideoMessageResult:) name:equesOnMessageVideoplayingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeCallNotification) name:@"CloseCallNotification" object:nil];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    [self.callTimer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc{
    NSLog(@"销毁");
}

#pragma mark 收到的消息
- (void)onVideoMessageResult:(NSNotification *)notification{
    NSLog(@"视频的消息");
    [self.loadingView removeFromSuperview];
    [self.callTimer invalidate];

    self.canOperate= YES;
    if (!self.timer) {
        NSLog(@"计时");
        [self performSelectorOnMainThread:@selector(startCount) withObject:nil waitUntilDone:YES];

    }

}

-(void)startCount{

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerSelector) userInfo:nil repeats:YES];
}

//超时
-(void)startCallCount{

    self.callTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(callTimerSelector) userInfo:nil repeats:YES];
}

- (void)onMessageResult:(NSNotification *)notification{
    NSDictionary *messageResult = [notification object];

    NSLog(@"收到的消息%@",messageResult);
    NSString *method = messageResult[@"method"];
    NSString *state = messageResult[@"state"];
    if ([method isEqualToString:@"relay"]&&[state isEqualToString:@"ok"]) {
        [YKBusinessFramework equesAudioPlayEnable:YES];

    }else if ([method isEqualToString:@"call"]&&[state isEqualToString:@"close"]) {
        [SVProgressHUD showInfoWithStatus:@"通话关闭"];
        [self hangupAction:nil];

    }else if ([method isEqualToString:@"filetrans"]){
        NSString *fid = messageResult[@"fid"];
        NSString *from = messageResult[@"from"];
        NSURL *url = [YKBusinessFramework equesGetRingPictureUrl:from fid:fid];
        [self.videoView sd_setImageWithURL:url placeholderImage:nil options:SDWebImageAllowInvalidSSLCertificates];
    }
    

}

- (void)timerSelector{
    NSLog(@"timerSelector");
    self.seconds++;
    self.timeLabel.text =  [self getMMSSFromSS:self.seconds];
}

- (void)callTimerSelector{
    NSLog(@"callTimerSelector");
    self.callSeconds++;
    if (self.callSeconds>=120) {
        [SVProgressHUD showInfoWithStatus:@"连接超时"];
        [self hangupAction:nil];
    }
}

-(NSString *)getMMSSFromSS:(NSInteger )seconds{

    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];

    return format_time;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) myspeakButtonPressed:(UILongPressGestureRecognizer *)gesture
{

    if (gesture.state == UIGestureRecognizerStateBegan) {
        [YKBusinessFramework equesAudioRecordEnable:true];
        [self.speakButton setTitle:@"松开结束" forState:UIControlStateNormal];
        self.speakButton.backgroundColor = UIColorFromRGB(0XF18D2A);
    }
    else if (gesture.state == UIGestureRecognizerStateEnded) {
        [YKBusinessFramework equesAudioRecordEnable:false];
        self.speakButton.backgroundColor = [UIColor whiteColor];

        [self.speakButton setTitle:@"按住说话" forState:UIControlStateNormal];
    }
}


- (IBAction)hangupAction:(id)sender {
    [self.timer invalidate];
    [self.callTimer invalidate];

    AudioServicesDisposeSystemSoundID(self.soundID);

    [YKBusinessFramework equesCloseCall:self.sid];
    [self dismissViewControllerAnimated:YES completion:nil];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isPlaying = NO;
}

- (IBAction)captureAction:(id)sender {
    
    if (!self.canOperate) {
        
        return;
    }
    
    //获取Documents文件夹目录
    NSString *path = [ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];


    [self.dateFormatter setDateFormat:@"yy-MM-dd"];

    NSString *dateString = [self.dateFormatter stringFromDate:[NSDate date]];


    //获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //指定新建文件夹路径
    path = [[[path stringByAppendingPathComponent:@"capture"] stringByAppendingPathComponent:self.bid ] stringByAppendingPathComponent:dateString];

    if (![fileManager fileExistsAtPath:path]) {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    [self.dateFormatter setDateFormat:@"yy-MM-dd hh:mm:ss"];
    dateString = [self.dateFormatter stringFromDate:[NSDate date]];
    NSString * imagePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",dateString]];

    [YKBusinessFramework equesSnapCapture:1 fileurl:imagePath];
    [SVProgressHUD showSuccessWithStatus:@"抓拍成功"];

}
- (IBAction)vedioOrAudioPlay:(id)sender {

    AudioServicesDisposeSystemSoundID(self.soundID);

    UIButton *b = sender;
    if (b.tag==0) {
        [self.callView setHidden:NO];
        [self.callingView setHidden:YES];
        [self.callCommingView setHidden:YES];
        self.sid = [YKBusinessFramework equesOpenCall:self.bid showView:self.videoView enableVideo:YES];

    }else{
//        self.canOperate = YES;
        [self.callView setHidden:YES];
        [self.callingView setHidden:NO];
        [self.callCommingView setHidden:YES];
        self.videoView.hidden = YES;
        self.sid = [YKBusinessFramework equesOpenCall:self.bid showView:self.videoView enableVideo:YES];

    }
}

- (IBAction)audioSwitchAction:(id)sender {


    if (!self.canOperate) {
        
        return;
    }

    UIButton *b = sender;
    [YKBusinessFramework equesAudioPlayEnable:b.selected];
    b.selected=!b.selected;
    
    if (b.selected) {
        [SVProgressHUD showSuccessWithStatus:@"已开启静音"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"已取消静音"];

    }

}
@end
